/**
 * 图像马赛克处理相关工具函数
 */
/**
 * 应用马赛克效果到指定的矩形区域
 * @param ctx Canvas渲染上下文
 * @param x 起始X坐标
 * @param y 起始Y坐标
 * @param width 区域宽度
 * @param height 区域高度
 * @param blockSize 基础马赛克块大小，默认为10像素
 */
export const applyMosaic = (
  ctx: CanvasRenderingContext2D, 
  x: number, 
  y: number, 
  width: number, 
  height: number, 
  blockSize: number = 7
): void => {
  // 确保坐标和尺寸为整数
  x = Math.floor(x)
  y = Math.floor(y)
  width = Math.floor(width)
  height = Math.floor(height)

  // 根据图片尺寸动态调整 blockSize
  const maxDimension = Math.max(width, height)
  const scaleFactor = Math.min(10, Math.floor(maxDimension / 100))
  const dynamicBlockSize = Math.max(blockSize, blockSize * scaleFactor)

  // 获取区域像素数据
  const imageData = ctx.getImageData(x, y, width, height)
  const data = imageData.data

  // 按块应用马赛克
  for (let blockY = 0; blockY < height; blockY += dynamicBlockSize) {
    for (let blockX = 0; blockX < width; blockX += dynamicBlockSize) {
      // 确保不会超出区域边界
      const blockW = Math.min(dynamicBlockSize, width - blockX)
      const blockH = Math.min(dynamicBlockSize, height - blockY)

      if (blockW <= 0 || blockH <= 0) continue

      // 计算块的平均颜色
      let r = 0, g = 0, b = 0, count = 0

      for (let py = 0; py < blockH; py++) {
        for (let px = 0; px < blockW; px++) {
          const i = ((blockY + py) * width + (blockX + px)) * 4
          r += data[i]
          g += data[i + 1]
          b += data[i + 2]
          count++
        }
      }

      // 计算平均值
      r = Math.floor(r / count)
      g = Math.floor(g / count)
      b = Math.floor(b / count)

      // 将块内所有像素设置为平均颜色
      for (let py = 0; py < blockH; py++) {
        for (let px = 0; px < blockW; px++) {
          const i = ((blockY + py) * width + (blockX + px)) * 4
          data[i] = r
          data[i + 1] = g
          data[i + 2] = b
          // Alpha通道保持不变
        }
      }
    }
  }

  // 将处理后的数据放回Canvas
  ctx.putImageData(imageData, x, y)
}
/**
 * 将画布内容转换为Blob对象
 * @param canvas Canvas元素
 * @param mimeType 输出的MIME类型，默认为'image/jpeg'
 * @param quality 图像质量（0-1），仅用于JPEG格式
 * @returns Promise，解析为Blob对象或null
 */
export const canvasToBlob = (
  canvas: HTMLCanvasElement,
  mimeType: string = 'image/jpeg',
  quality: number = 0.9
): Promise<Blob | null> => {
  return new Promise((resolve) => {
    canvas.toBlob(resolve, mimeType, quality)
  })
}
/**
 * 加载图像到Canvas
 * @param file 图像文件
 * @param canvas 主Canvas元素
 * @param previewCanvas 预览Canvas元素（可选）
 * @returns Promise，解析为void
 */
export const loadImageToCanvas = (
  file: File,
  canvas: HTMLCanvasElement,
  previewCanvas?: HTMLCanvasElement
): Promise<void> => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    
    img.onload = () => {
      // 设置Canvas尺寸
      canvas.width = img.width
      canvas.height = img.height
      
      // 绘制到主Canvas
      const ctx = canvas.getContext('2d')
      if (!ctx) {
        reject(new Error('无法获取Canvas上下文'))
        return
      }
      ctx.drawImage(img, 0, 0)
      
      // 如果提供了预览Canvas，也绘制到预览Canvas
      if (previewCanvas) {
        previewCanvas.width = img.width
        previewCanvas.height = img.height
        
        const previewCtx = previewCanvas.getContext('2d')
        if (!previewCtx) {
          reject(new Error('无法获取预览Canvas上下文'))
          return
        }
        previewCtx.drawImage(img, 0, 0)
      }
      
      resolve()
    }
    
    img.onerror = () => {
      reject(new Error('图片加载失败'))
    }
    
    img.src = URL.createObjectURL(file)
  })
}